// pages/shop/show.js

import {
    makePhoneCall,
    datetimeFormat
} from '../../utils/util'

import {
    getSellerInfo,
    getReviews,
    comment,
} from '../../utils/apis'

const {
    $Toast
} = require('../../dist/base/index');

var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();

var initOrder = {
    totalNum: 0,
    totalPrice: 0,
    totalGoodsPrice: 0,
    totalPackingFee: 0,
    goodsNums: {},
    goods: []
}

var app = getApp();
Page({
    data: {
        current: 'tab1',
        current_scroll: 'tab1',
        comments: [],
        userComment: '',
        review: {
            hasMore: true,
            list: [],
            page: 0,
            loading: false
        },
        shopInfo: {
            discount: 0.9,
            avatar: '',
            name: ''
        },
    },

    handleChange({
        detail
    }) {
        this.setData({
            current: detail.key
        });
    },
    onLoad: function(options) {
        var current = JSON.parse(options.current);
        this.id = current.id || 1;
        this.descriptionId = current.description || 1;
        this.setData({
            'shopInfo.discount': current.discount,
            'shopInfo.avatar': current.avatar,
            'shopInfo.name': current.name,
        });
        this.loadData();
        this.loadReview();
    },
    onReady: function() {
        // 页面渲染完成
    },
    onShow: function() {
        // 页面显示
    },
    onHide: function() {
        // 页面隐藏
    },
    onUnload: function() {
        // 页面关闭
    },

    loadData() {
        var that = this;
        var id = this.id;
        wx.showNavigationBarLoading();
        getSellerInfo({
            descriptionId: this.descriptionId,
            success(data) {
                // that.setData({
                //     detail: data.content
                // });
                WxParse.wxParse('article', 'html', data.content, that, 5);
                wx.hideNavigationBarLoading();
            }
        })
    },

    loadReview() {
        var that = this;
        var id = this.id;
        var {
            review: {
                page,
                loading
            }
        } = this.data;
        if (loading) {
            return;
        }

        this.setData({
            'review.loading': true
        });
        getReviews({
            data: {
                offset: page,
                sellerId: id,
                uid: app.globalData.loginInfo.id,
            },
            success(data) {
                var {
                    review: {
                        list,
                        page
                    }
                } = that.data;
                that.setData({
                    'review.list': list ? list.concat(data.list) : data.list,
                    'review.loading': false,
                    'review.page': page + 1,
                    'review.hasMore': data.list.length === 10
                })
            }
        })
    },

    addComment() {
        var that = this;
        var {
            loginInfo
        } = app.globalData;

        // 未注册
        if (!loginInfo || JSON.stringify(loginInfo) === '{}') {
            $Toast({
                content: '还没有注册，不能评论哦!'
            });
            return;
        }
        comment({
            data: {
                'content': this.data.userComment,
                'sellerId': this.id,
                'uid': app.globalData.loginInfo.id,
            },
            success() {
                var wxUserInfo = wx.getStorageSync('wxUserInfo');
                that.data.review.list.unshift({
                    nickname: wxUserInfo.nickName,
                    content: that.data.userComment,
                    time: (new Date()).getDate(),
                    avatar: wxUserInfo.avatarUrl,
                });
                that.setData({
                    'review.list': that.data.review.list,
                    'userComment': ''
                })
            }
        });
    },
    onReachBottom(e) {
        if (this.data.review.hasMore && !this.data.review.loading) {
            this.loadReview();
        }
    },

    onCommentChange({
        detail: {
            detail: {
                value
            }
        }
    }) {
        this.setData({
            userComment: value,
        })
    },
    tabClick: function(e) {
        this.setData({
            activeIndex: e.currentTarget.id
        });
    },

    swiperChange(e) {
        var {
            current
        } = e.detail
        this.setData({
            activeIndex: current
        })
    },
    menuClick: function(e) {
        this.setData({
            activeMenuIndex: e.currentTarget.id
        })
    },

    addGoods(goods, item) {
        var {
            goods_id,
            sub_id,
            num
        } = item
        var itemIndex;
        if (sub_id) {
            itemIndex = goods.findIndex(item => {
                return item['goods_id'] == goods_id && item['sub_id'] == sub_id
            })
        } else {
            itemIndex = goods.findIndex(item => {
                return item['goods_id'] == goods_id
            })
        }
        if (itemIndex >= 0) {
            goods[itemIndex]['num'] += num
        } else {
            goods.push(item)
        }
        return goods
    },
    onGotUserInfo({
        detail: {
            userInfo
        }
    }) {
        var info = app.globalData.wxUserInfo;
        if (!info || JSON.stringify(info) === '{}') {
            wx.setStorageSync('wxUserInfo', userInfo);
            app.globalData.wxUserInfo = userInfo;
        }
        this.addComment();
    },
    onPhoneTap(e) {
        var {
            phone
        } = e.currentTarget.dataset
        makePhoneCall(phone)
    },

    onScrolltolower(e) {
        var {
            hasMore,
            loading
        } = this.data.review
        if (hasMore && !loading) {
            this.loadReview()
        }
    },
    onAddQuasiOrder(e) {
        var that = this
        var {
            info: {
                seller_id
            },
            order: {
                goods
            },
            loading
        } = this.data
        if (loading) {
            return
        }

        this.setData({
            loading: true
        })
        getApp().getLoginInfo(loginInfo => {
            if (!loginInfo.is_login) {
                wx.navigateTo({
                    url: '/pages/login/login',
                })
                this.setData({
                    loading: false
                })
                return
            }
            addQuasiOrder({
                seller_id,
                goods,
                success(data) {

                    that.setData({
                        loading: false
                    })
                    wx.navigateTo({
                        url: `/pages/order/quasi?id=${data.quasi_order_id}`
                    })
                },
                error() {
                    that.setData({
                        loading: false
                    })
                }
            })
        })
    },
    onShareAppMessage() {
        var {
            info: {
                seller_id,
                seller_name
            }
        } = this.data
        return {
            title: seller_name,
            path: `/pages/shop/show?id=${seller_id}`
        }
    }
})